<?php

/**
 * 策略模式
 * 优化过多的ifelse和switch
 *
 * 示例解决一个根据订单类型处理商品信息
 *
 */

class OrderSuccessHandle
{
    public $orderInfo;

    const ORDER_TYPE = [
        '10' => 'BatteryDep', //电池押金
        '11' => 'BatteryRent', //电池租金
        '20' => 'BikeDep',//电动车押金
        '21' => 'BikeRent',//电动车押金
    ];

    public function __construct($orderInfo)
    {
        if (empty($orderInfo)) {
            throw new Error('order info cannot be empty!');
        }

        if (!is_array($orderInfo)) {
            throw new Error('order info must be array!');
        }

        $this->orderInfo = $orderInfo;
    }

    /**
     * handle
     *
     * @param
     * @return void
     */
    public function handle()
    {
        if (!$this->orderInfo['type']) {
            throw new Error("orderInfo type cannot be empty!");
        }

        $class_name = self::ORDER_TYPE[$this->orderInfo['type']];

        call_user_func([new $class_name, 'orderHandle']);
    }
}

/**
 * 处理电池押金
 */
class BatteryDep{
    public function orderHandle(){
        echo '处理电池押金完成'.PHP_EOL;
    }
}

/**
 * 处理电池押金
 */
class BatteryRent{
    public function orderHandle(){
        echo '处理电池租金完成'.PHP_EOL;
    }
}

/**
 * 处理电动车押金
 */
class BikeDep{
    public function orderHandle(){
        echo '处理电动车押金完成'.PHP_EOL;
    }
}

/**
 * 处理电动车租金
 */
class BikeRent{
    public function orderHandle(){
        echo '处理电动车租金完成'.PHP_EOL;
    }
}


$orderInfo = ['type'=>10];
$obj = new OrderSuccessHandle($orderInfo);
$obj->handle();

$orderInfo = ['type'=>11];
$obj = new OrderSuccessHandle($orderInfo);
$obj->handle();

$orderInfo = ['type'=>21];
$obj = new OrderSuccessHandle($orderInfo);
$obj->handle();

$orderInfo = ['type'=>20];
$obj = new OrderSuccessHandle($orderInfo);
$obj->handle();